package com.distribute.core.netty.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.distribute.common.MsgObj;
import com.distribute.common.MsgType;
import com.distribute.common.ReportEntity;
import com.distribute.core.core.CacheManageContext;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 启动成功监听器
 *
 * @author chennengcheng
 * @date 2021-09-13 17:01
 * @remark
 */
public class ConnectSuccessListener implements GenericFutureListener<ChannelFuture> {

    private static final Logger log = LoggerFactory.getLogger(ConnectSuccessListener.class);

    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
        log.info("Netty init over,result:{}", future.isSuccess());
        if (future.isSuccess()){
            reportSelf(future);
        }
    }

    /**
     * 初始化回调
     */
    public void reportSelf(ChannelFuture future){
        List<ReportEntity> reportEntityList = CacheManageContext.getReportEntityList();
        if (CollectionUtil.isEmpty(reportEntityList)) {
            return;
        }

        MsgObj msgObj = new MsgObj(MsgType.CACHE_INFO_TYPE, JSONUtil.toJsonStr(reportEntityList));
        String msg = JSONUtil.toJsonStr(msgObj);
        ByteBufAllocator alloc = future.channel().alloc();
        ByteBuf encoded = alloc.buffer(4 * msg.length());
        encoded.writeBytes(msg.getBytes());
        future.channel().write(encoded);
        future.channel().flush();
    }
}
